package com.github.yoojia.mqtt.boot.utils;

import com.github.yoojia.mqtt.boot.Config;
import com.parkingwang.lang.ThrowSupplier;
import com.parkingwang.lang.Try;
import com.parkingwang.lang.kit.StreamKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.file.Paths;
import java.util.Map;

/**
 * 配置加载器
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.3
 */
public class ConfigKit {

    public static final Logger LOGGER = LoggerFactory.getLogger(ConfigKit.class);

    private ConfigKit(){}

    @SuppressWarnings("unchecked")
    public static Config stream(final InputStream stream){
        return Try.die(new ThrowSupplier<Config>() {
            @Override
            public Config call() throws Throwable {
                return new Config((Map<String, Object>) new Yaml().load(stream));
            }
        });
    }

    /**
     * 加载指定名称的 Resources 目录下的文件
     * @param name Resources 目录下的文件名
     * @return Config
     */
    public static Config resource(final String name){
        return Try.die(new ThrowSupplier<Config>() {
            @Override
            public Config call() throws Throwable {
                InputStream stream = null;
                try{
                    stream = ConfigKit.class.getResourceAsStream(name);
                    return stream(stream);
                }finally {
                    if (stream != null) {
                        stream.close();
                    }
                }
            }
        });
    }

    public static void extractByName(final String srcName, final String outputName){
        final String dir = System.getProperty("user.dir");
        Try.die(new ThrowSupplier<Boolean>() {
            @Override
            public Boolean call() throws Throwable {
                final File outputFile = Paths.get(dir, outputName).toFile();
                if ( ! outputFile.exists()){
                    LOGGER.info("!!! FBI WARNING !!!");
                    LOGGER.info("A default config is extracting to path: {}", outputFile.getAbsolutePath());
                    try(InputStreamReader input = new InputStreamReader(ConfigKit.class.getResourceAsStream(srcName));
                        OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(outputFile))){
                        StreamKit.copy(input, output);
                    }
                }
                return true;
            }
        });
    }

}
